import struct
import sys

def outASM(file,out,address,size):
	file.seek(address);
	offset	=	0;
	while offset + 0x10 <= size :
		data0	= '0x%08x'%struct.unpack("I",file.read(4));
		data1	= '0x%08x'%struct.unpack("I",file.read(4));
		data2	= '0x%08x'%struct.unpack("I",file.read(4));
		data3	= '0x%08x'%struct.unpack("I",file.read(4));
		off		= '0x%08x'%offset
		datastr	=	"    .int  %s,%s ,%s,%s       @%s"%(data0,data1,data2,data3,off)
		print datastr
		offset	+=	0x10;
	while offset < size:
		data0	= '0x%02x'%struct.unpack("B",file.read(1));
		off		= '0x%08x'%offset
		datastr	=	"    .byte %s                                               @%s" %(data0,off);
		print datastr;
		offset	+=	1;
	return offset;

class Chunk:
	def __init__(self,addr,size,type,filename,info):
		self.addr	=	addr;
		self.size	=	size;
		self.type	=	type;
		self.file	=	filename;
		self.info	=	info;

chunks	=	[];

def add_chunk(addr,size,type,filename,info):
	chunks.append(Chunk(addr,size,type,filename,info));
	

	
class FileOut:
	def __init__(self,file,size,chunk):
		self.file	=	file;
		self.size	=	size;
		self.offset	=	0;
		self.chunks	=	chunk;
		self.chunkindex	=	0;
	def outASM(self,out):
		osize	=	self.size;
		self.out(out,osize);
	def out(self,out,size):
		endoffset	=	self.offset + size;
		while self.offset < endoffset:
			cchunk	=	self.chunks[self.chunkindex];
			if cchunk != None:
				if cchunk.addr >= self.offset and cchunk.addr < self.size:
					outsize	=	self.offset - cchunk.addr;
					self.offset		+=	outASM(self.file,out,self.offset,outsize);
					infostr			=	cchunk.info;
					if out == None:
						print infostr;
					else:
						out.writelines(infoset);
					outsize			=	cchunk.size;
					ofile			=	None;
					if cchunk.file !='' and cchunk.file != None:
						ofile		=	open(cchunk.file,'w+');
					self.chunkindex	+=	1;
					self.out(ofile,outsize);
					if ofile 		!= None:
						ofile.close();
					#end------
				#end-------
			else:
				outsize		=	endoffset	-	self.offset;
				self.offset	+=	outASM(self.file,out,self.offset,outsize);
		print '@=======\n';
		
		
			
			
		
	

def BIN2s(file,out,address,size) :
	file.seek(0,2);
	filesize	=	file.tell();
	if size <= 0:
		size	=	filesize;
	#chunks.sort(lambda x,y:cmp(x.addr,y.addr));
	chunks.sort(key = lambda x:x.addr);
	chunkindex	=	0;
	oo			=	FileOut(file,size,chunks);
	oo.outASM(out);

	
	
	
	
add_chunk(0x20,0,0,"","4567");
add_chunk(0x10,0,0,"","4567");
add_chunk(0x40,0,0,"","4567");
add_chunk(0x30,0,0,"","4567");
# chunks.sort(key = lambda x:x.addr);

# print chunks[0].addr;
# print chunks[1].addr;
# print chunks[2].addr;
# print chunks[3].addr;


if len(sys.argv) < 2:
	print 'error:  binaryfile [outfile]>[outfile]'
	exit();
	
	
print "@out binary file:" + sys.argv[1];
file	=	open(sys.argv[1],"rb");
#outASM(file,None,0,0x24);
BIN2s(file,None,0,0);


file.close();


